import subprocess
import os
import signal
import shutil
import psutil

# 根据进程名查询进程id
def is_process_running(process_name):
    process_list = []
    for process in psutil.process_iter(['name']):
        try:
            if process.info['name'] and process_name.lower() in process.info['name'].lower():
                process_list.append(process.pid)
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            continue
    return process_list

# 批量结束进程
def kill_process(pids):
    for pid in pids:
        if int(pid):
            os.kill(int(pid), signal.SIGINT)

# 根据端口查询进程id
def get_pid(port):
    pids = []
    command = f"netstat -aon | findstr :{port}"
    process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
    output, _ = process.communicate()
    output = output.decode('utf-8').strip()
    if output:
        lines = output.split('\n')
        for line in lines:
            columns = line.split()
            if len(columns) >= 5:
                pids.append(columns[-1])
    return list(set(pids))

# 删除过期日志
def remove_old_log(path, cutoff_time):
    for item in os.listdir(path):
        item_path = os.path.join(path, item)
        item_ctime = os.path.getctime(item_path)
        if item_ctime < cutoff_time:
            if os.path.isfile(item_path):
                os.remove(item_path)
            elif os.path.isdir(item_path):
                shutil.rmtree(item_path)

# 获取目标路径（如果没有直接创建）
def ensure_directory_exists(path):
    if not os.path.exists(path):
        os.makedirs(path)
    return path
